package com.example.liyuehui.pluginlib;

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by LiYueHui on 2017/11/19.
 */

public class WriteFooTask extends DefaultTask {
    private FooData fooData;
    private File targetDir;
    private String fileName;

    @Nested
    public FooData getFooData() {
        return fooData;
    }

    @OutputFile
    public File getTargetFile(){
        return new File(targetDir,fileName);
    }

    @Input
    public String getFileName() {
        return fileName;
    }

    @InputDirectory
    public File getTargetDir() {
        return targetDir;
    }

    @TaskAction
    public void writeObject(){
        File targetFile = new File(targetDir,fileName);
        try {
            FileOutputStream fos = new FileOutputStream(targetFile);
            byte[] bytes = fooData.toString().getBytes();
            fos.write(bytes);
            fos.flush();
            fos.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setFooData(FooData fooData) {
        this.fooData = fooData;
    }

    public void setTargetDir(File targetDir) {
        this.targetDir = targetDir;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
